TARGET = application
BUILD_DIR = build
OPT = -Og
DEBUG = 0
PREFIX = arm-none-eabi-
CC = $(PREFIX)gcc
AS = $(PREFIX)gcc -x assembler-with-cpp
SZ = $(PREFIX)size
CP = $(PREFIX)objcopy
AR = $(PREFIX)ar
HEX = $(CP) -O ihex
BIN = $(CP) -O binary -S
CPU = -mcpu=cortex-m0
MCU = $(CPU) -mthumb $(FPU) $(FLOAT-ABI)
C_DEFS = \
-DSTM32F030xC \
-DUSE_HAL_DRIVER

ASM_SOURCES = 

C_SOURCES = $(wildcard main/*.c)
C_SOURCES += $(wildcard bsp/*.c)
C_SOURCES += $(wildcard app/littlefs/*.c)
C_SOURCES += $(wildcard app/ota/*.c)
C_SOURCES += $(wildcard app/mtask/*.c)
C_SOURCES += $(wildcard app/com/*.c)
C_SOURCES += $(wildcard app/stdcrc16/*.c)
C_SOURCES += $(wildcard app/iap_update/*.c)
C_SOURCES += $(wildcard app/modbus/*.c)
C_SOURCES += $(wildcard app/shake_measurement/*.c)

C_SOURCES += $(wildcard device/iis2dlpc/*.c)
C_SOURCES += $(wildcard device/lis2dh12/*.c)
C_SOURCES += $(wildcard device/mma8451q/*.c)

C_INCLUDES = \
-Idrivers/CMSIS/Include \
-Idrivers/CMSIS/Device/ST/STM32F0xx/Include \
-Idrivers/STM32F0xx_HAL_Driver/Inc \
-Ibsp \
-Iapp \
-Idevice

ASFLAGS = $(MCU) $(AS_DEFS) $(AS_INCLUDES) $(OPT) -Wall -fdata-sections -ffunction-sections
CFLAGS = $(MCU) $(C_DEFS) $(C_INCLUDES) $(OPT) -Wall -fdata-sections -ffunction-sections -std=c99
ifeq ($(DEBUG), 1)
CFLAGS += -g -gdwarf-2
endif
CFLAGS += -MMD -MP -MF"$(@:%.o=%.d)"

LDSCRIPT = bsp/STM32F030CCTx_FLASH.ld
LIBS =  -lstm32f030xc -larm_cortexM0l_math -lc -lm -lnosys
LIBDIR = -Llib -Ldrivers/CMSIS/Lib/GCC
LDFLAGS = $(MCU) -specs=nano.specs -T$(LDSCRIPT) $(LIBDIR) $(LIBS) -Wl,-Map=$(BUILD_DIR)/$(TARGET).map,--cref -Wl,--gc-sections

BOOT_FILE = $(notdir $(wildcard ./bootloader*.bin))

all: library $(BUILD_DIR)/$(TARGET).elf $(BUILD_DIR)/$(TARGET).bin
ifeq ($(shell uname), Linux)
	@./app_packet $(BOOT_FILE)
else
	@./app_packet.exe $(BOOT_FILE)
endif

OBJECTS = $(addprefix $(BUILD_DIR)/,$(notdir $(C_SOURCES:.c=.o)))
vpath %.c $(sort $(dir $(C_SOURCES)))
OBJECTS += $(addprefix $(BUILD_DIR)/,$(notdir $(ASM_SOURCES:.s=.o)))
vpath %.s $(sort $(dir $(ASM_SOURCES)))

$(BUILD_DIR)/%.o: %.c Makefile | $(BUILD_DIR) 
	@$(info $(notdir $@))
	@$(CC) -c $(CFLAGS) -Wa,-a,-ad,-alms=$(BUILD_DIR)/$(notdir $(<:.c=.lst)) $< -o $@

$(BUILD_DIR)/%.o: %.s Makefile | $(BUILD_DIR)
	@$(info $(notdir $@))
	@$(AS) -c $(ASFLAGS) $< -o $@

$(BUILD_DIR)/$(TARGET).elf: $(BUILD_DIR) $(OBJECTS) Makefile
	@$(CC) $(OBJECTS) $(LDFLAGS) -o $@
	@$(SZ) $@

$(BUILD_DIR)/%.bin: $(BUILD_DIR)/%.elf | $(BUILD_DIR)
	@$(BIN) $< $@
	@$(info $(notdir $@))

$(BUILD_DIR):
	@mkdir -p $@

clean: 
	@rm -rf $(BUILD_DIR)
	@rm -rf lib
	@cd drivers && $(MAKE) clean

library:
	@cd drivers && $(MAKE) -j8

rebuild: clean library all

-include $(wildcard $(BUILD_DIR)/*.d)
